package com.mgr.controller;

import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.mgr.model.Customers;
import com.mgr.service.CustomerService;
import java.util.ResourceBundle;
import nl.captcha.Captcha;

@Controller
public class LoginController {

	/**
	 * @param custService the custService to set
	 */
	public void setCustService(CustomerService custService) {
		this.custService = custService;
	}

	@Autowired
	private CustomerService custService;

	private ResourceBundle rb = ResourceBundle
			.getBundle("com.mgr.messages.errorMessage");

	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public ModelAndView process(@RequestParam("custId") String id,
			@RequestParam("custPass") String pw,
			@RequestParam("answer") String answer, HttpSession session,
			Map<String, String> map) {

		Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
		String message = "";
		ModelAndView modView = new ModelAndView();
		try {
			if (!captcha.isCorrect(answer)) {
				message = rb.getString("captchaWrong");
			} else if (!custService.checkLogin(Integer.parseInt(id), pw)) {
				message = rb.getString("idpassWrong");
			}

			if (message.isEmpty()) {
				session.setAttribute("user", id);
				String userName = custService
						.getCustomers(Integer.parseInt(id)).getCustName();
				session.setAttribute("userName", userName);
				modView.setViewName("redirect:mainpage");
			} else {
				modView.setViewName("login");
				modView.addObject("message", message);
				modView.addObject("idTemp", id);
			}
		} catch (NumberFormatException e) {
			modView.setViewName("login");
			message = rb.getString("numberLarge");
			modView.addObject("message", message);
			modView.addObject("idTemp", id);
		}
		return modView;
	}

	@RequestMapping("/register")
	public String getRegisterPage(Map<String, Object> map, HttpSession session) {
		Customers customer = new Customers();
		map.put("customer", customer);
		return "register";
	}

}
